<template>
  <a-drawer :open="visible" destroyOnClose title="装车单详情" :width="1200" :body-style="{ paddingBottom: '80px', backgroundColor: '#F9F9F9' }" @close="onClose">
    <template #closeIcon>
      <close @on-close="onClose" />
    </template>
    <template #extra>
      <a-space :size="5">
        <span>{{ options.no }}</span>
        <span>配送司机：{{ options.driver?.name }}</span>
        <span>协送员：{{ options.escortDriver?.name }}</span>
        <span>{{ getDescByValue('DELIVERY_STATUS_ENUM', options.status) }}</span>
        <span>{{ options.create_time }}</span>
        <a-button type="link" @click="changeLogModal(true)" :disabled="true">查看日志</a-button>
        <a-button @click="printDelivery">
          <template #icon>
            <PrinterOutlined />
          </template>
          打印配送单({{ printLog?.print_count ?? 0 }})
        </a-button>
      </a-space>
    </template>
    <a-card size="small" title="基本信息">
      <a-descriptions size="small" :column="3">
        <a-descriptions-item label="单据编号">{{ options.no }}</a-descriptions-item>
        <a-descriptions-item label="配送司机">{{ options.driver?.name }}</a-descriptions-item>
        <a-descriptions-item label="装车状态">
          <span>{{ getDescByValue('DELIVERY_STATUS_ENUM', options.status) }}</span>
        </a-descriptions-item>
        <a-descriptions-item label="协送员">{{ options.escortDriver?.name }}</a-descriptions-item>
        <a-descriptions-item label="制单员">{{ options.creator?.username }}</a-descriptions-item>
      </a-descriptions>
    </a-card>
    <a-card size="small" class="smart-margin-top10" title="统计信息">
      <a-descriptions size="small" :column="3">
        <a-descriptions-item label="订单数量"> {{ options.order_num }}</a-descriptions-item>
        <a-descriptions-item label="商品金额"> {{ options.delivery_amount }}</a-descriptions-item>
        <a-descriptions-item label="商品数量"> {{ options.delivery_num }}</a-descriptions-item>
        <a-descriptions-item label="商品体积"> 销：{{ options.sale_total_volume.toFixed(2) }}m³ 退：{{ options.return_total_volume.toFixed(2) }}m³</a-descriptions-item>
        <a-descriptions-item label="商品重量"> 销：{{ options.sale_total_weight.toFixed(2) }}kg 退：{{ options.return_total_weight.toFixed(2) }}kg</a-descriptions-item>
      </a-descriptions>
    </a-card>
    <a-card class="smart-margin-top10" size="small" :tab-list="tabList" :active-tab-key="activeKey" @tabChange="(key) => (activeKey = key)">
      <template #customTab="{ tab }">
        <span class="ant-card-head-title" :style="compactModeClass">
          {{ tab }}
        </span>
      </template>
      <template v-if="activeKey === 'inventory'">
        <DeliveryOrderTable ref="OrderTable" :orderList="orderList" :row="options" @onSelectChange="onOrderSelectChange" @reloadList="detail(options)" />
      </template>
      <template v-if="activeKey === 'goods'">
        <DeliveryGoodsTable :rowId="options.id" />
      </template>
    </a-card>
    <template #footer>
      <a-button @click="onClose" style="margin-right: 8px">取消</a-button>
      <template v-if="activeKey === 'inventory'">
        <a-button type="primary" style="margin-right: 8px" :disabled="selectedRows.length === 0" @click="print(options)">合并打印</a-button>
        <!-- <a-button type="primary" style="margin-right: 8px" :disabled="selectedRows.length === 0" @click="picking('all')">合并拣货</a-button> -->
        <!-- <a-button type="primary" style="margin-right: 8px" :disabled="selectedRows.length === 0" @click="picking('sign')">逐单拣货</a-button> -->
      </template>
    </template>
    <!---------- 打印 end ----------->
    <PickingPrintModal ref="printRef" />
    <DeliveryPrintModal ref="printDeliveryRef" />
    <a-modal v-model:open="showPickingModal" title="提示信息" okText="剔除并保存" @ok="createPickOrder">
      <a-tooltip>
        <template #title>
          <p v-once v-for="no in pickedOrders.map(({ no }) => no)">
            {{ no }}
          </p>
        </template>
        <div v-once style="width: 100%; height: 1.25em; white-space: nowrap; text-overflow: ellipsis; overflow: hidden">
          {{ pickedOrders.map(({ no }) => no).join('、') }}
        </div>
        <p
          >以上<span style="color: red" v-once>{{ pickedOrders.length }}</span
          >个订单已生成拣货任务，无法再次提交</p
        >
      </a-tooltip>
    </a-modal>
  </a-drawer>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import _ from 'lodash'
import PickingPrintModal from './picking-print-modal.vue'
import DeliveryPrintModal from './delivery-print-modal.vue'
import { useEnums } from '@/hooks/plugins/useEnums'
import { useTransformSpec } from '@/hooks/web/use-transform-spec'
import { GOODS_UNIT_TYPE } from '@/constants/business/goods-const'
import DeliveryGoodsTable from './delivery-goods-table.vue'
import DeliveryOrderTable from './delivery-order-table.vue'
import { taskApi } from '@/api/business/logistics/delivery-api'
import { pickOrderApi } from '@/api/business/storage/picking-api'
import { message, Modal } from 'ant-design-vue'
import { errorSentry } from '@/lib/error-sentry'
const compactModeClass = inject('compactModeClass')
const { getDescByValue } = useEnums()
const { transformSpec } = useTransformSpec()
defineExpose({
  showDrawer
})
const emit = defineEmits(['refresh', 'reload-list'])

// --------------------- Drawer 显示与隐藏 ---------------------
// 是否展示
const visible = ref(false)
// 详情
const options = ref({})
const printLog = ref({})

function showDrawer(item) {
  options.value = item
  detail(item)
  visible.value = true
}
const orderList = ref([])
const detail = async (rowData) => {
  try {
    const res = await taskApi.detailLoad({ id: rowData.id })
    orderList.value = res.data.data || []
    printLog.value = res.data.printLog || {}
  } catch (e) {
    if (e.data.length == 0) {
      onClose()
      emit('reload-list')
    }
    // message.error(e.msg)
    errorSentry.captureError(e)
  }
}
// 详情tab
const activeKey = ref('inventory')
const tabList = [
  {
    key: 'inventory',
    tab: '订单明细'
  },
  {
    key: 'goods',
    tab: '商品明细'
  }
]

const onClose = () => {
  visible.value = false
  orderGoodsList.value = []
  selectedRows.value = []
}
const route = useRoute()
watch(
  () => route.fullPath,
  () => {
    onClose()
  }
)
// ---------------------------- 订单列表选择 ----------------------------
const OrderTable = useTemplateRef('OrderTable')
const selectedRows = shallowRef([])
function onOrderSelectChange(selectRows) {
  // handleSelectOrders(selectRows)
  selectedRows.value = selectRows
}

// ---------------------------- 打印 ----------------------------
const printRef = ref()
let orderGoodsList = shallowRef<any[]>([])
let orderGoodsTotal = {
  price: 0,
  num: ''
}
function handleSelectOrders(selectedRows) {
  let totalPrice = 0
  const chartMap = new Map([
    ['整'.charCodeAt(0), 0],
    ['中'.charCodeAt(0), 0],
    ['散'.charCodeAt(0), 0]
  ])
  const unitTypeMap = {
    [GOODS_UNIT_TYPE.LARGE.value]: '整'.charCodeAt(0),
    [GOODS_UNIT_TYPE.MIDDLE.value]: '中'.charCodeAt(0),
    [GOODS_UNIT_TYPE.SMALL.value]: '散'.charCodeAt(0)
  }
  function handleGoodsData(data) {
    const { goods, type, batch_info, remark } = data[0]
    const base_num = _.sumBy(data, 'base_num')
    return {
      goods_name: goods.goods_name,
      type,
      total_units: transformSpec(base_num, goods.spec),
      batch_time: dayjs(batch_info.batch_time).format('YYYY-MM-DD'),
      location_code: batch_info.location_code,
      remark
    }
  }
  function handleTotalData(data) {
    const key = unitTypeMap[data.spec.unit_type]
    const sourceNum = chartMap.get(key)
    chartMap.set(key, sourceNum + data.num)
    totalPrice += Number(data.total_price)
    return data
  }
  function handleRowData(data: any[]) {
    const { warehouse } = data[0]
    return _(data)
      .map('detail')
      .flatMapDeep()
      .map(handleTotalData)
      .groupBy('goods_id')
      .mapValues(handleGoodsData)
      .mapValues((item) => {
        return {
          ...item,
          warehouse_name: `${warehouse.name}(${warehouse.warehouse_attribute_name})`
        }
      })
      .values()
      .value()
  }
  orderGoodsList.value = _(selectedRows).groupBy('warehouse_id').mapValues(handleRowData).values().flatMapDeep().value()
  orderGoodsTotal = {
    price: totalPrice,
    num: _(Array.from(chartMap.entries()))
      .map(([chinese, number]) => {
        if (number === 0) return ''
        return `${number}${String.fromCharCode(chinese as number)}`
      })
      .join('')
  }
}
const print = () => {
  const ids = selectedRows.value.map((item) => item.id).join(',')
  printRef.value.showDrawer(options.value.id, ids)
}

// ---------------------------- 打印 配送单 ----------------------------
const printDeliveryRef = ref()
function printDelivery() {
  printDeliveryRef.value.showDrawer(options.value)
}

// ---------------------------- 拣货 ----------------------------
const showPickingModal = ref(false)
const pickedOrders = computed(() => {
  return selectedRows.value.filter((row) => row.isPick)
})
const unpickedOrders = computed(() => {
  return selectedRows.value.filter((row) => !row.isPick)
})

const createPickingOrdersData = {
  load_order_id: '',
  type: 1,
  source_orders: [],
  remark: ''
}
function picking(type: 'all' | 'sign') {
  if (pickedOrders.value.length > 0) {
    showPickingModal.value = true
  } else {
    Modal.confirm({
      title: '确认生成拣货单？',
      onOk: createPickOrder
    })
  }
  createPickingOrdersData.type = type === 'all' ? 1 : 2
}

async function createPickOrder() {
  try {
    if (unpickedOrders.value.length === 0) {
      throw {
        msg: '没有可拣货的订单'
      }
    }
    // 剔除已拣货订单选择
    if (pickedOrders.value.length > 0) {
      OrderTable.value?.clearSelectedKeys(pickedOrders.value.map((item) => item.id))
      await nextTick()
    }
    createPickingOrdersData.load_order_id = options.value.id
    createPickingOrdersData.source_orders = unpickedOrders.value.map((order) => ({
      related_id: order.id,
      related_type: 2
    }))
    const res = await pickOrderApi.create(createPickingOrdersData)
    message.success(res.msg)
    detail(options.value)
    OrderTable.value?.clearSelectedKeys()
  } catch (error) {
    message.error(error.msg)
    errorSentry.captureError(error)
  } finally {
    showPickingModal.value = false
  }
}
</script>
